package questionnaire

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"h8QuestionnaireServer/database/dao"
	"h8QuestionnaireServer/database/entity"
	"h8QuestionnaireServer/pojo/response"
	"h8QuestionnaireServer/service"
	"io/ioutil"
	"net/http"
	"time"
)

func SelectQuestionnaireData(ctx *gin.Context){

	token := ctx.Request.URL.Query().Get("token")
    code := "admin"
	if token == "" || len(token) <= 0{
		resp:= response.GenLoser("参数无效")
		ctx.JSON(http.StatusOK,resp)
		return
	}

	dicts,err := service.GetQuestionDataServer(token,code)

	if err == nil{
		if dicts == nil{
			resp := response.GenLoser("null")
			ctx.JSON(http.StatusOK,resp)
		}else {
			resp := response.GenSuccess(dicts)
			ctx.JSON(http.StatusOK, resp)
		}
	}else{
		resp := response.GenLoser(err)
		ctx.JSON(http.StatusOK,resp)
	}

}
func InsertQuestionnaire(ctx *gin.Context){

	dict := new(entity.DictQuestionnaire)
	byte,err:=ioutil.ReadAll(ctx.Request.Body)
	if len(byte)<=0 ||err != nil{
		resp := response.GenLoser("参数获取失败")
		ctx.JSON(http.StatusOK,resp)
		return
	}
	json.Unmarshal(byte,&dict)

	if dict.Content == ""{
		resp := response.GenLoser("参数解析失败，内容为空")
		ctx.JSON(http.StatusOK,resp)
		return
	}

	result,id,err := service.InsertQuestionDataServer(dict.Content,dict.Version)
	if result == 99{

		resp := response.GenSuccessPost("主键重复，请重试",id)
		ctx.JSON(http.StatusOK,resp)
	}else if err == nil && result == 1{

		resp := response.GenSuccessPost("提交成功",id)
		ctx.JSON(http.StatusOK,resp)
	}else {
		resp := response.GenLoser(err)
		ctx.JSON(http.StatusOK,resp)
	}
}

func UserLogin(ctx *gin.Context)  {

	byte,err :=ioutil.ReadAll(ctx.Request.Body)
	if err != nil || byte == nil || len(byte) <= 0{
		resp:= response.GenLoser("参数无效")
		ctx.JSON(http.StatusOK,resp)
		return
	}
	userinfo := make(map[string]string)
	err = json.Unmarshal(byte,&userinfo)
	if err != nil || userinfo == nil{
		resp:= response.GenLoser("参数无效")
		ctx.JSON(http.StatusOK,resp)
	}
	var ret bool
	ret,err = service.CheckLogin(userinfo["username"],userinfo["password"])
	if err != nil || !ret  {
		resp:= response.GenLoser("工号或密码错误")
		ctx.JSON(http.StatusOK,resp)
	}else{
		emp, _ := dao.GetLoginInfo(userinfo["username"])
		dict := new(entity.DictEmployee)
		emp_token := service.IsExpired(emp)
		if emp_token != "" {
			dict.Token = emp_token
		}else{
			dict.Token = service.Snowflake.GenId()
		}
		dict.Code = userinfo["username"]
		dict.LimitTime = time.Now()
		//err := service.SaveToken(dict.Code,dict.Name,dict.Token,dict.LimitTime)
		err := service.SaveToken(dict)
		if err != nil{
			resp:= response.GenLoser("tk验证失败")
			ctx.JSON(http.StatusOK,resp)
			return
		}
		resp:= response.GenSuccess(dict.Token)
		ctx.JSON(http.StatusOK,resp)
	}
}
